﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpPcap;
using SharpPcap.Packets;
using System.IO;

namespace WeaponEvalue
{
    public partial class MainForm : Form
    {
        private List<PcapDevice> devices;
        private PcapDevice deviceSelected;
        private string localAddress;
        private int packetCount;
        private int total;
        private int total1;
        private DateTime start;


        //31 02 00 00 00 00
        private byte[] sig = new byte[] {0xE8,0x0B,0x76,0x00};
        private byte[] sig2 = new byte[]{ 0xA4,0x06,0x00,0x00,0x00,0x00};

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            devices=Pcap.GetAllDevices();
            deviceComboBox.DataSource = devices;
            deviceComboBox.DisplayMember = "Description";
        }

        private void deviceComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void captureButton_Click(object sender, EventArgs e)
        {
            int deviceIndex=deviceComboBox.SelectedIndex;
            if (deviceIndex < 0)
            {
                return;
            }
            else
            {
                packetCount = 0;
                total = 0;
                total1 = 0;
                start = DateTime.Now;
                captureButton.Enabled = false;
                stopButton.Enabled = true;
                deviceSelected = devices[deviceIndex];
                deviceSelected.OnPacketArrival += new Pcap.PacketArrivalEvent(deviceSelected_OnPacketArrival);
                localAddress = deviceSelected.Addresses[0].Addr.ToString();
                deviceSelected.Open(true, 1000);
                deviceSelected.StartCapture();
            }

        }

        void deviceSelected_OnPacketArrival(object sender, PcapCaptureEventArgs e)
        {
            Packet packet = e.Packet;
            if (packet is TCPPacket)
            {
                DateTime time = packet.Timeval.Date;
                uint len = packet.PcapHeader.PacketLength;

                TCPPacket tcp = (TCPPacket)packet;

                string srcIp = tcp.SourceAddress.ToString();

                string dstIp = tcp.DestinationAddress.ToString();

                int srcPort = tcp.SourcePort;

                int dstPort = tcp.DestinationPort;
                
                if (localAddress.Equals(dstIp))
                {
                    DealData(tcp.Data);
                    packetCount++;
                    SetControlText(packetCountLabel, string.Format("{0}个", packetCount));
                }
            }
        }

        private void DealData(byte[] p)
        {
            int index=FindTarget(p, 0, sig);
            while (index >= 0)
            {
                int d = 0;
                d += p[index + 42];
                d += p[index + 43]*256;
                d += p[index + 44]*256*256;
                d += p[index + 45]*256*256*256;
                total += d;
                AppendControlText(dataTextBox, "we are god-伤害："+d+"\r\n");
                double seconds=(DateTime.Now-start).TotalSeconds;
                SetControlText(totalLabel, (total / seconds).ToString());
                index = FindTarget(p, index+25, sig);
            }
            index = FindTarget(p, 0, sig2);
            while (index >= 0)
            {
                int d = 0;
                d += p[index + 22];
                d += p[index + 23] * 256;
                d += p[index + 24] * 256 * 256;
                d += p[index + 25] * 256 * 256 * 256;
                total1 += d;
                AppendControlText(dataTextBox, "we are god-受到伤害：" + d + "\r\n");
                double seconds = (DateTime.Now - start).TotalSeconds;
                SetControlText(totalLabel1, (total1 / seconds).ToString());
                index = FindTarget(p, index + 25, sig2);
            }
        }

        private int FindTarget(byte[] p, int startIndex, byte[] sig)
        {
            int index = -1;
            for (int i = startIndex; i < p.Length; i++)
            {
                bool isTarget = true;
                for (int j = 0; j < sig.Length; j++)
                {
                    if (i + j >= p.Length)
                    {
                        isTarget = false;
                        break;
                    }
                    if (p[i + j] != sig[j])
                    {
                        isTarget = false;
                        break;
                    }
                }
                if (!isTarget)
                {
                    continue;
                }
                else
                {
                    index = i;
                    break;
                }
            }
            return index;
        }


        private void stopButton_Click(object sender, EventArgs e)
        {
            if (deviceSelected != null)
            {
                try
                {
                    captureButton.Enabled = true;
                    stopButton.Enabled = false;
                    deviceSelected.StopCapture();
                    deviceSelected.Close();
                }
                catch (Exception ex)
                {
                    deviceSelected.Close();
                }
            }
        }

        public delegate void setControlTextDelegate(Control control, string text);

        private void SetControlText(Control control,string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new setControlTextDelegate(SetControlText),new object[]{control,text});
            }
            else
            {
                control.Text = text;
            }
        }

        public delegate void appendControlTextDelegate(Control control, string text);

        private void AppendControlText(Control control, string text)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new appendControlTextDelegate(AppendControlText), new object[] { control, text });
            }
            else
            {
                control.Text += text;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FormAbout about = new FormAbout();
            about.ShowDialog(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            total = 0;
            total1 = 0;
            packetCount = 0;
            packetCountLabel.Text = string.Empty;
            totalLabel.Text = string.Empty;
            totalLabel1.Text = string.Empty;
            dataTextBox.Text = string.Empty;
            start = DateTime.Now;
        }
       

    }
}